import { Catch, ArgumentsHost, Inject } from '@nestjs/common';
import { Response, Request } from 'express';
import { AppError, transError } from '.';

@Catch()
export class AllExceptionsFilter  {
    // constructor(
    //     @Inject('LOGGER' ) private readonly logger,
    //   ) {}
    catch(exception: unknown, host: ArgumentsHost) {
        const error = transError(exception);
        const ctx = host.switchToHttp();
        const request = ctx.getRequest<Request>();
        const response = ctx.getResponse<Response>();
        response
            .status(error.statusCode)
            .json({
                error: {
                    statusCode: error.statusCode,
                    name: error.name,
                    message: error.message,
                    code: error.code,
                },
            });
        // this.accesslogError(request, error);
    }
    accesslogError(req: Request, error: AppError) {
        if (req.method === 'GET') { return; }
        const now =  new Date().toISOString().substr(0, 19) + 'Z';
        const id = req.params.id ? req.params.id : null;
        let log;
        log = {
            notify_timestamp: now,
            notify_type : 'operation',
            deviceModel: '',
            paramCode: '',
            deviceID: '',
            msg_body: {
                method: req.method,
                url: req.baseUrl + decodeURIComponent(req.path),
                userName: req.query.userName  ,
                userId: req.query.userId,
                statusCode:  error.statusCode || 406,
                error: (typeof error.message === 'string') ? error.message : JSON.stringify(error.message),
            },
        };
        if (req.path.substr(1, 10) === 'strategies') {
            log.msg_body.strategyId = id;
        } else if (req.path.substr(1, 6) === 'faults') {
            log.msg_body.faultId = id;
        } else {
            log.msg_body.id = id;
        }
        // this.logger.error.error(JSON.stringify(log));
    }
}
